import  {defineStore} from 'pinia'

export const moduleCart=defineStore('cartList',{
  state:()=>{
    return {cart:JSON.parse(uni.getStorageSync('cart') || '[]') }
  },
  actions:{
    addToCart(goods){
      const findResult=this.cart.find((x)=>x.goods_id===goods.goods_id)
      if(!findResult){
        this.cart.push(goods)
      }else{
        findResult.goods_count++
      }  
     this.saveToStorage()
    },
    saveToStorage(){
      uni.setStorageSync('cart',JSON.stringify(this.cart))
    },
    updateGoodsState(goods){
      const findResult=this.cart.find((x)=>x.goods_id===goods.goods_id)
      if(findResult){
        findResult.goods_state=goods.goods_state
        this.saveToStorage()
      }
    },
    updateGoodsCount(goods){
       const findResult=this.cart.find((x)=>x.goods_id===goods.goods_id)
       if(findResult){
         findResult.goods_count=goods.goods_count
         this.saveToStorage()
       }
    },
    removeGoodsById(goods_id){
      this.cart=this.cart.filter(x=>x.goods_id!==goods_id)
      this.saveToStorage()
    },
    updateAllGoodsState(newState){
     
      this.cart.forEach(x=>x.goods_state=newState)
      this.saveToStorage()
    }
    
  },
  getters:{
    total(){
     //  let c=0
     //  this.cart.forEach(goods=>c+=goods.goods_count)
     
     //  return c
    return this.cart.reduce((total,item)=>total+=item.goods_count,0)
    },
    checkCount(){
      return this.cart.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count,0)
    },
    checkedGoodsAmount(){
      return this.cart.filter(x=>x.goods_state).reduce((total,item)=>total+=item.goods_count*item.goods_price,0).toFixed(2)
    }
  }
})